package cn.e3mall.cart.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.e3mall.cart.service.CartService;
import cn.e3mall.common.utils.CookieUtils;
import cn.e3mall.common.utils.E3Result;
import cn.e3mall.common.utils.JsonUtils;
import cn.e3mall.pojo.TbItem;
import cn.e3mall.pojo.TbUser;
import cn.e3mall.service.ItemService;

@Controller
public class CartController {

	@Autowired
	private ItemService itemService;
	
	@Value("${COOKIE_CART_EXPIRE}")
	private Integer COOKIE_CART_EXPIRE;	//购物车cookie的有效时间
	
	@Autowired
	private CartService cartService;
	
	@RequestMapping("/cart/add/{itemId}")
	public String addCart(@PathVariable Long itemId, @RequestParam(defaultValue="1")Integer num,
			HttpServletRequest request, HttpServletResponse response) {
		TbUser user = (TbUser) request.getAttribute("user");
		if(user != null) {	//用户登录状态
			//把商品添加到服务器（redis）,把用户id，商品id，商品数量传入
			cartService.addCart(user.getId(),itemId,num);
			
			//返回成功逻辑视频
			return "cartSuccess";
		}
		//查询cookie中的购物车列表
		List<TbItem> cartList = getCartListFromCookie(request);
		
		boolean flag = false; //标识商品是否存在于购物车列表
		//存在则数量相加
		
		//判断列表中是否存在该商品
		for(TbItem item:cartList) {
			//若商品在列表中
			if(item.getId() == itemId.longValue()) {
				//数量相加
				item.setNum(item.getNum() + num);
				flag = true;
				//跳出循环
				break;
			}
		}
		
		//不存在查询商品信息
		if(!flag) {
			//查询商品信息
			TbItem item = itemService.getItemById(itemId);
			
			//设置商品数量
			item.setNum(num);
			
			//取第一张图片
			String image = item.getImage();
			
			if(StringUtils.isNotBlank(image)) {
				item.setImage(image.split(",")[0]);
			}
			//向列表中添加商品
			cartList.add(item);
		}
		//向cookie中写入购物车列表
		CookieUtils.setCookie(request, response, "cart", JsonUtils.objectToJson(cartList), COOKIE_CART_EXPIRE, true);
		
		return "cartSuccess";
	}
	
	/**
	 * 	cookie中取购物车列表
	 */
	public List<TbItem> getCartListFromCookie(HttpServletRequest request){
		
		//从cookie取购物车列表
		String cart = CookieUtils.getCookieValue(request,"cart", true);
		
		//若购物车为空
		if(StringUtils.isBlank(cart)) return new ArrayList<TbItem>(); //返回一个空的购物车列表
		
		return JsonUtils.jsonToList(cart, TbItem.class);
	}
	
	/**
	 * 展示购物车列表
	 * <p>Title: showCatList</p>
	 * <p>Description: </p>
	 * @param request
	 * @return
	 */
	@RequestMapping("/cart/cart")
	public String showCatList(HttpServletRequest request, HttpServletResponse response) {
		//从cookie中取购物车列表
		List<TbItem> cartList = getCartListFromCookie(request);
		
		TbUser user = (TbUser) request.getAttribute("user");
		
		if(user != null) {	//用户登录状态
			//如果购物车不为空就合并购物车
			if(cartList != null || cartList.size() >0) {
				cartService.mergeCart(user.getId(),cartList);
				//删除购物车
				CookieUtils.deleteCookie(request, response, "cart");
			}
			
			//获取购物车列表放到request中
			cartList = cartService.getCartListFromDB(user.getId());
		}

		//把列表传递给页面
		request.setAttribute("cartList", cartList);
		//返回逻辑视图
		return "cart";
	}
	
	/**
	 * 更新购物车商品数量
	 */
	@RequestMapping("/cart/update/num/{itemId}/{num}")
	@ResponseBody
	public E3Result updateCartNum(@PathVariable Long itemId, @PathVariable Integer num
			, HttpServletRequest request ,HttpServletResponse response) {
		//判断用户是否登录
		TbUser user = (TbUser) request.getAttribute("user");
		
		if(user != null) {	//用户登录状态
			//登录就更新redis中的商品数量
			cartService.updateItemNumFromDBCart(user.getId(),itemId,num);
			
			return E3Result.ok();
		}
		//从cookie中取购物车列表
		List<TbItem> cartList = getCartListFromCookie(request);
		//遍历商品列表找到对应的商品
		for (TbItem tbItem : cartList) {
			if (tbItem.getId().longValue() == itemId) {
				//更新数量
				tbItem.setNum(num);
				break;
			}
		}
		//把购物车列表写回cookie
		CookieUtils.setCookie(request, response, "cart", JsonUtils.objectToJson(cartList), COOKIE_CART_EXPIRE, true);
		//返回成功
		return E3Result.ok();
	}
	
	/**
	 * 删除购物车商品
	 */
	@RequestMapping("/cart/delete/{itemId}")
	public String deleteCartItem(@PathVariable Long itemId, HttpServletRequest request,
			HttpServletResponse response) {
		//判断用户是否登录
		TbUser user = (TbUser) request.getAttribute("user");
		
		if(user != null) {	//用户登录状态
			//登录就删除redis中的商品
			cartService.deleteItemFromDBCart(user.getId(),itemId);
			//重定向购物车展示列表
			return "redirect:/cart/cart.html";
		}
		
		//从cookie中取购物车列表
		List<TbItem> cartList = getCartListFromCookie(request);
		//遍历列表，找到要删除的商品
		for (TbItem tbItem : cartList) {
			if (tbItem.getId().longValue() == itemId) {
				//删除商品
				cartList.remove(tbItem);
				//跳出循环
				break;
			}
		}
		//把购物车列表写入cookie
		CookieUtils.setCookie(request, response, "cart", JsonUtils.objectToJson(cartList), COOKIE_CART_EXPIRE, true);
		//返回逻辑视图
		return "redirect:/cart/cart.html";
	}

}
